﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Csla;

namespace Aiss.Sync
{
    [Serializable]
    public class Column:BusinessBase<Column>
    {
        string name = "";
        string dBType = "";
        private bool isNullable = true;
        private bool selected = false;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        public string DBType
        {
            get { return dBType; }
            set { dBType = value; }
        }

        public bool IsNullable
        {
            get { return isNullable; }
            set { isNullable = value; }
        }
        
        public bool Selected
        {
            get { return selected; }
            set { selected = value; }
        }

        public Column(string name, string dBType)
        {
            this.name = name;
            this.dBType = dBType;
        }

        private Column()
        {

        }

        public static Column GetColumn(Csla.Data.SafeDataReader dr)
        {
            Column c = new Column();
            c.Fetch(dr);
            return c;
        }

        private void Fetch(Csla.Data.SafeDataReader dr)
        {
            name = dr.GetString("name");
            isNullable = dr.GetBoolean("is_nullable");
            selected = isNullable == false;
        }

        public static System.ComponentModel.BindingList<string> GetColumns(string tableName)
        {
            System.ComponentModel.BindingList<string> tables = new System.ComponentModel.BindingList<string>();
            using (System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(Settings.ConnStringMain))
            {
                con.Open();
                try
                {
                    System.Data.SqlClient.SqlCommand cm = con.CreateCommand();
                    cm.CommandType = System.Data.CommandType.Text;
                    cm.CommandText = @"select Name from sys.columns 
where sys.columns.object_id in (SELECT object_id FROM sys.objects
where type = N'U' AND Name = @TableName)";
                    cm.Parameters.AddWithValue("@TableName",tableName);

                    System.Data.SqlClient.SqlDataReader dr = cm.ExecuteReader();
                    while (dr.Read())
                    {
                        tables.Add(dr.GetString(0));
                    }
                }
                catch (Exception ex)
                {
                }
            }

            return tables;
        }
    }
}
